//JavaScript代码区域
layui.use(['element', 'table', 'jquery', 'laydate', 'form'], function () {
    var element = layui.element;
    var table = layui.table;
    var laydate = layui.laydate;
    var form = layui.form;
    laydate.render({
        elem: "#start_date"
    })
    laydate.render({
        elem: "#end_date"
    })
    $(function () {
        getCode();
        getRoleList();
        tableRender();
        form.render();
    })
    $("#find").click(function () {
        tableRender();
    })
    $("#clear").click(function () {
        $(".search_input").val("");
    })

    function tableRender() {
        table.render({
            elem: '#demo'
            // , height: 312
            ,
            url: LOCALHOSTURL + '/user/getUsers' //数据接口
            ,
            method: "get",
            where: {
                "param": $("#param").val(),
                "sex": $("#sex").find("option:selected").val(),
                "graduate": $("#graduate").find("option:selected").val(),
                "role": $("#role").find("option:selected").val(),
                "start_date": $("#start_date").val(),
                "end_date": $("#end_date").val()
            },
            xhrFields: {
                withCredentials: true //默认情况下，标准的跨域请求是不会发送cookie的
            },
            headers: {
                "Authorization": $.cookie("token")
            },
            crossDomain: true,
            response: {
                statusName: 'code' //规定数据状态的字段名称，默认：code
                ,
                statusCode: 200 //规定成功的状态码，默认：0
            },
            page: true, //开启分页
            title: "用户表",
            toolbar: '#toolbar',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [
                [ //表头
                    {
                        type: 'checkbox',
                        fixed: 'left'
                    }, {
                    field: 'id',
                    title: 'ID',
                    sort: true
                }, {
                    field: 'code',
                    title: '用户编号'
                }, {
                    field: 'name',
                    title: '用户姓名',
                    templet: function (res) {
                        if (res.name == null)
                            return '暂无';
                        else
                            return res.name;
                    }
                }, {
                    field: 'phone',
                    title: '电话',
                    templet: function (res) {
                        if (res.phone == null)
                            return '暂无';
                        else
                            return res.phone;
                    }
                }, {
                    field: 'address',
                    title: '所在地址',
                    templet: function (res) {
                        if (res.address == null)
                            return '暂无';
                        else
                            return res.address;
                    }
                }, {
                    field: 'sex',
                    title: '性别',
                    templet: function (res) {
                        if (res.sex == null)
                            return '暂无';
                        else
                            return res.sexName;
                    }
                }, {
                    field: 'graduate',
                    title: '学历',
                    templet: function (res) {
                        if (res.graduate == null)
                            return '暂无';
                        else
                            return res.graduateName;
                    }
                }, {
                    field: 'entranceTime',
                    title: '入学时间',
                    sort: true,
                    templet: function (res) {
                        if (res.entranceTime == null)
                            return '暂无';
                        else
                            return res.entranceTime;
                    }
                },{
                    field: 'role',
                    title: '角色',
                    templet: function (res) {
                        if (res.role == null)
                            return '暂无';
                        else
                            return res.roleName;
                    }
                }, {
                    field: 'icon',
                    title: '头像',
                    templet: function (res) {
                        return '<img class="layui-nav-img" width="30px" height="30px" src="' + res.icon + '"/>'
                    }
                }, {
                    field: 'status',
                    title: '状态'
                }, {
                    fixed: 'right',
                    title: '操作',
                    toolbar: '#barDemo',
                    width: 100
                }
                ]
            ]
        });
    }

    //第一个实例

    table.on('toolbar(demo)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'add':
                layer.open({
                    type: 2,
                    title: "添加用户信息",
                    area: ['100%', '100%'],
                    content: ["editUser.html"],
                    shadeClose: true, //点击旁边地方自动关闭
                    //动画
                    anim: 0,
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                        body.find("#code").removeAttr("readonly");
                        body.find("#update").html("添加");
                        body.find("#update").click(function () {
                            let code = body.find("#code").val();
                            let password = body.find("#password").val();
                            let cfmpsd = body.find("#cfmpassword").val();
                            if (code == '') {
                                layer.msg("用户编号不能为空", function () {
                                    body.find("#code").focus();
                                })
                            } else if (code != '') {
                                let result = myAjax("/user/getUserByName", "get", {"username": code});
                                if (result.data == null) {
                                    if (password == '') {
                                        layer.msg("用户密码不能为空", function () {
                                            body.find("#password").focus();
                                        })
                                    } else if (password != cfmpsd) {
                                        layer.msg("两次密码输入不一致", function () {
                                            body.find("#password").focus();
                                        })
                                    } else {
                                        let userdata = {
                                            "code": code,
                                            "name": body.find("#name").val(),
                                            "password": password,
                                            "phone": body.find("#phone").val(),
                                            "sex": body.find("#sex").find("option:selected").val(),
                                            "graduate": body.find("#graduate").find("option:selected").val(),
                                            "role": body.find("#role").find("option:selected").val(),
                                            "entranceTime": body.find("#entranceTime").val(),
                                            "icon": body.find("#icon").attr("src")
                                        };
                                        console.log(userdata);
                                        let result = ajaxModel("/user/register", "post", userdata);
                                        if (result.code == 200) {
                                            layer.alert(result.message, {icon: 1});
                                            tableRender();
                                            layer.close(index);

                                        } else
                                            layer.alert(result.message, {icon: 1});
                                    }
                                } else {
                                    layer.msg("该用户编号已存在");
                                    body.find("#code").focus();
                                }
                            }
                        });
                        body.find("#cancel").click(function () {
                            layer.close(index);
                        });
                    }
                })
                break;
        }
        ;
    });

    //监听行工具事件
    table.on('tool(demo)', function (obj) {
        var data = obj.data;
        console.log(obj);
        if (obj.event === 'del') {
            layer.confirm("真的删除用户" + data.code + "?", function (index) {
                // obj.del();
                let result = myAjax("/user/deleteUser", "get", {code: data.code});
                alert(result.message);
                tableRender();
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            // layer.alert(JSON.stringify(obj.data));
            layer.open({
                type: 2,
                title: "修改用户信息",
                area: ['100%', '100%'],
                content: ["editUser.html"],
                shadeClose: true, //点击旁边地方自动关闭
                //动画
                anim: 0,
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                    //给表单赋值
                    body.find("#code").val(data.code);
                    body.find("#name").val(data.name);
                    // body.find("#password").val(data.password);
                    body.find("#phone").val(data.phone);
                    body.find("#address").val(data.address);
                    body.find("#sex").find("option[value='" + data.sex + "']").attr("selected", true);
                    body.find("#graduate").find("option[value='" + data.graduate + "']").attr("selected", true);
                    body.find("#role").find("option[value='" + data.role + "']").attr("selected", true);
                    body.find("#entranceTime").val(data.entranceTime);
                    body.find("#icon").attr("src", data.icon);
                    body.find("#update").click(function () {
                        let password = body.find("#password").val();
                        let cfmpsd = body.find("#cfmpassword").val();
                        if (password != cfmpsd) {
                            layer.msg("两次密码输入不一致", function () {
                                body.find("#password").focus();
                            })
                        } else {
                            let userdata = {
                                "id": data.id,
                                "code": body.find("#code").val(),
                                "name": body.find("#name").val(),
                                "password": body.find("#password").val(),
                                "phone": body.find("#phone").val(),
                                "address": body.find("#address").val(),
                                "sex": body.find("#sex").find("option:selected").val(),
                                "graduate": body.find("#graduate").find("option:selected").val(),
                                "role": body.find("#role").find("option:selected").val(),
                                "entranceTime": body.find("#entranceTime").val(),
                                "icon": body.find("#icon").attr("src")
                            };
                            console.log(userdata);
                            let result = ajaxModel("/user/updateUser", "post", userdata);
                            layer.alert(result.message, {icon: 1});
                            if (result.code == 200) {
                                tableRender();
                                layer.close(index);
                                // layer.close();
                            }
                        }
                    });
                    body.find("#cancel").click(function () {
                        layer.close(index);
                    });
                    iframeWin.layui.form.render();
                }
            })
        }
    });

    form.on('switch(status)', function (obj) {
        var data = obj.value;
        var checked = obj.elem.checked;
        let result = "";
        if (checked) {
            result = myAjax("/user/updateStatus", "post", {"code": data, "status": 'normal'});
        } else {
            result = myAjax("/user/updateStatus", "post", {"code": data, "status": 'frozen'});
        }
        console.log(result.data);
        // tableRender();
    });

    //获取码表数据
    function getCode() {
        let data = null;
        if (sessionStorage.getItem("code") != null) {
            data = JSON.parse(sessionStorage.getItem("code"));
        } else {
            let result = ajaxModel("/user/getCodeList", "get");
            data = result.data;
            sessionStorage.setItem("code", JSON.stringify(data));
        }
        console.log(data);
        $("#sex").html("<option value=''>全部</option>");
        $.each(data.sex, function (i, sex) {
            $("#sex").append("<option value='" + sex.code + "'>" + sex.name + "</option>");
        })
        $("#graduate").html("<option value=''>全部</option>");
        $.each(data.graduate, function (i, graduate) {
            $("#graduate").append("<option value='" + graduate.code + "'>" + graduate.name + "</option>");
        })
    }

    function getRoleList() {
        let data = null;
        if (sessionStorage.getItem("role") != null) {
            data = JSON.parse(sessionStorage.getItem("role"));
        } else {
            let result = ajaxModel("/role/getRoleList", "get");
            data = result.data;
            sessionStorage.setItem("role", JSON.stringify(data));
        }
        console.log(data);
        $("#role").html("<option value=''>全部</option>");
        $.each(data, function (i, role) {
            $("#role").append("<option value='" + role.id + "'>" + role.name + "</option>");
        });
    }
});
